<?php

namespace app\common\model;

use Houdunwang\Arr\Arr;
use think\Model;
use think\Validate;

class Category extends Model
{

    /**
     * 添加栏目
     *
     * @param $post
     *
     * @return array
     */
    public function add($post)
    {
        $validate = new Validate([
            'name|栏目名称' => 'require',
            'pid|父级id' => 'require|number',
            'sort|排序' => 'number'
        ]);
        if (!$validate->check($post)) {
            return ['code' => 0, 'message' => $validate->getError()];
        }
        $this->save([
            'name' => $post['name'],
            'pid' => $post['pid'],
            'sort' => $post['sort'],
        ]);
        return ['code' => 1, 'message' => '栏目添加成功'];
    }

    /**
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getAll()
    {
        $data = db('category')->order('sort', 'asc')->select();
        return (new Arr())->tree($data, 'name', 'id', 'pid');
    }

    /**
     * 编辑栏目
     *
     * @param $post
     *
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function edit($post)
    {
        $validate = new Validate([
            'id|栏目id' => 'require',
            'name|栏目名称' => 'require',
            'sort|排序' => 'number'
        ]);
        if (!$validate->check($post)) {
            return ['code' => 0, 'message' => $validate->getError()];
        }
        $res = $this->find($post['id']);

        $res->save([
            'name' => $post['name'],
            'sort' => $post['sort'],
        ]);
        return ['code' => 1, 'message' => '栏目修改成功'];
    }
}
